package tool

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"sort"
)

// GenerateSignature 根据给定的参数和商户密钥生成签名
func GenerateSignature(params map[string]interface{}, secret string) (string, error) {
	// 将参数按照键名ASCII码排序
	keys := make([]string, 0, len(params))
	for k := range params {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	// 构建排序后的参数字符串
	var sortedParamStr string
	for _, k := range keys {
		value := fmt.Sprintf("%v", params[k])
		sortedParamStr += value
	}

	// 拼接商户密钥
	strToSign := sortedParamStr + secret

	// 计算MD5并转换为小写字符串
	hasher := md5.New()
	_, err := hasher.Write([]byte(strToSign))
	if err != nil {
		return "", err
	}
	signature := hex.EncodeToString(hasher.Sum(nil))

	return signature, nil
}
